package com.p.lib.widget.imageview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

/**
 * 正方形的ImageView
 * Created by Administrator on 2018/6/7 0007.
 */

public class SqureImageView extends ImageView {

    /**
     * 宽度适应屏幕
     */
    private boolean fitScreenWidth = false;
    public void setFitScreenWidth(boolean fitScreenWidth) {
        this.fitScreenWidth = fitScreenWidth;
    }
    public SqureImageView(Context context) {
        super(context);
        init();
    }
    public SqureImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public SqureImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init(){
		/*post(new Runnable() {
			@Override
			public void run() {
				LayoutParams lp = getLayoutParams();
				lp.width = getMeasuredWidth();
				lp.height = getMeasuredWidth();
				setLayoutParams(lp);
			}
		});*/
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(getMeasuredWidth() != getMeasuredHeight()){
                    int width = getMeasuredWidth();
                    if(fitScreenWidth){
                        width = getResources().getDisplayMetrics().widthPixels;
                    }
                    ViewGroup.LayoutParams lp = getLayoutParams();
                    lp.width = width;
                    lp.height = width;
                    setLayoutParams(lp);
                }
            }
        });
    }

}
